import { http } from '@kit.NetworkKit'

let httpRequest = http.createHttp()
// let baseUrl = 'http://47.121.118.187:8360'

export function get<T>(url:string, params?:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    if(params) {
      url += "?" + Object.keys(params).map((k) => `${k}=${params[k]}`).join('&')
    }
    let headers = {}
    let token = AppStorage.get<string>('token')
    if (token) {
      headers['X-Hioshop-Token'] = token
    }
    httpRequest.request(url, {
      method:http.RequestMethod.GET,
      header: headers
    })
      .then((r) => {
        if (r.responseCode == 200) {
          resolve(JSON.parse(r.result as string))
        } else {
          reject(new Error(`网络错误: ${r.responseCode}}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}
export function post<T>(url: string, params?:Object):Promise<T> {
  return new Promise<T>((resolve, reject) => {
    let headers = { 'Content-Type': 'application/json'}
    let token = AppStorage.get<string>('token')
    if (token) {
      headers['X-Hioshop-Token'] = token
    }
    httpRequest.request(url, {
      method: http.RequestMethod.POST,
      header: headers,
      extraData: params
    }).then(res => {
      if (res.responseCode === 200) {
        console.log('headers', JSON.stringify(res.header))
        resolve(JSON.parse(res.result as string))
      } else {
        reject(new Error(`网络错误：${res.responseCode}`))
      }
    })
      .catch(e => {
        reject(e)
      })
  })

}